package com.icez.layoutsliding

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import androidx.customview.widget.ViewDragHelper

open class LayoutSlidingLayout @JvmOverloads constructor(
    context: Context, val attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {
    //拖动帮助类
    private var mViewDragHelper:ViewDragHelper ?= null
    //拖动的view
    private var mContentView: View?= null
    //当前状态,默认停止状态
    private var mContentViewState:Int = ViewDragHelper.STATE_IDLE
    //划出方向,默认左边划出
    private var mLayoutSidingOrientation:LayoutSidingOrientation ?= LayoutSidingOrientation.BOTTOM
    //最小滑动速度
    private var mMinVelocity:Float = 200f

    var mContentViewXOffset = 0
    var mContentViewYOffset = 0

    override fun onFinishInflate() {
        super.onFinishInflate()
        if(childCount<=0||childCount>1){
            throw RuntimeException("必须需要一个内容布局，并且只能一个")
        }
        getStyleValue()
        //获取内容布局
        mContentView = getChildAt(0)

        //初始化拖动帮助类
        mViewDragHelper = ViewDragHelper.create(this,1f,mViewDragHelperCallback)
        when(mLayoutSidingOrientation){
            LayoutSidingOrientation.LEFT,LayoutSidingOrientation.RIGHT ->{
                //初始化可以拖动的方向
                this.mViewDragHelper?.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT or ViewDragHelper.EDGE_LEFT)
            }
            LayoutSidingOrientation.BOTTOM,LayoutSidingOrientation.TOP ->{
                //初始化可以拖动的方向
                this.mViewDragHelper?.setEdgeTrackingEnabled(ViewDragHelper.EDGE_TOP or ViewDragHelper.EDGE_BOTTOM)
            }
        }
        //设置最小速度
        mViewDragHelper?.minVelocity = mMinVelocity
    }

    /**
     * @sample 获取xml中的值
     */
    private fun getStyleValue(){
        val typeArray = context.obtainStyledAttributes(attrs,R.styleable.LayoutSlidingLayout)
        mMinVelocity = typeArray.getFloat(R.styleable.LayoutSlidingLayout_slider_minVelocity,200f)
        val orientation = typeArray.getInteger(R.styleable.LayoutSlidingLayout_slider_orientation,4)
        when(orientation){
            1 -> {
                mLayoutSidingOrientation = LayoutSidingOrientation.TOP
            }
            2 -> {
                mLayoutSidingOrientation = LayoutSidingOrientation.RIGHT
            }
            3 -> {
                mLayoutSidingOrientation = LayoutSidingOrientation.BOTTOM
            }
            4 -> {
                mLayoutSidingOrientation = LayoutSidingOrientation.LEFT
            }
        }
        typeArray.recycle()
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        //设置拖动范围
        mViewDragHelper?.edgeSize = width
        mContentView?.offsetLeftAndRight(mContentViewXOffset)
        mContentView?.offsetTopAndBottom(mContentViewYOffset)
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        //拦截事件交给帮助类
        return ev?.let { this.mViewDragHelper?.shouldInterceptTouchEvent(it) } ?:false
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event != null) {
            //触屏事件交给帮助类
            this.mViewDragHelper?.processTouchEvent(event)
        }
        return true
    }

    override fun computeScroll() {
        super.computeScroll()
        if(this.mViewDragHelper?.continueSettling(true)==true){
            invalidate()
        }else{
            mContentViewXOffset = mContentView?.left?:0
            mContentViewYOffset = mContentView?.top?:0
        }
    }

    private var mViewDragHelperCallback = object: ViewDragHelper.Callback() {
        override fun tryCaptureView(child: View, pointerId: Int): Boolean {
            return mContentView == child
        }

        override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int): Int {
            if(mContentView == child){
                var mLeft = left
                when(mLayoutSidingOrientation){
                    LayoutSidingOrientation.LEFT ->{
                        if(left>0){//不允许右边滑动
                            mLeft = 0
                        }else{//允许左滑动
                            mLeft = left
                        }
                        return mLeft
                    }
                    LayoutSidingOrientation.RIGHT ->{
                        if(left>0){//允许右边滑动
                            mLeft = left
                        }else{//不允许左滑动
                            mLeft = 0
                        }
                        return mLeft
                    }
                    LayoutSidingOrientation.BOTTOM,LayoutSidingOrientation.TOP ->{
                        mLeft = 0
                        return mLeft
                    }
                    else -> {
                        mLeft = 0
                        return mLeft
                    }
                }
            }else{
                return 0
            }

        }

        override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int {
            if(mContentView == child){
                var mTop = top
                when(mLayoutSidingOrientation){
                    LayoutSidingOrientation.LEFT,LayoutSidingOrientation.RIGHT ->{
                        mTop = 0
                        return mTop
                    }
                    LayoutSidingOrientation.BOTTOM->{
                        if(top>0){//下滑
                            mTop = top
                        }else{//上滑动
                            mTop = 0
                        }
                        return mTop
                    }
                    LayoutSidingOrientation.TOP ->{
                        if(top>0){//下滑
                            mTop = 0
                        }else{//上滑动
                            mTop = top
                        }
                        return mTop
                    }
                    else -> {
                        mTop = 0
                        return mTop
                    }
                }
            }else{
                return 0
            }
        }

        override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
            super.onViewReleased(releasedChild, xvel, yvel)
            if(mContentView == releasedChild){
                when(mLayoutSidingOrientation){
                    LayoutSidingOrientation.TOP -> {
                        val offset = releasedChild.bottom / releasedChild.height.toFloat()
                        if(offset>0.5){//下滑动
                            //设置捕获的控件的位置
                            mViewDragHelper?.settleCapturedViewAt(0,0)
                        }else if(offset<=0.5){//上滑动
                            //设置捕获的控件的位置
                            mViewDragHelper?.settleCapturedViewAt(0,-releasedChild.height)
                        }
                    }
                    LayoutSidingOrientation.RIGHT -> {
                        val offset = releasedChild.left / releasedChild.width.toFloat()
                        if(offset>0.5){//右边滑动
                            //设置捕获的控件的位置
                            mViewDragHelper?.settleCapturedViewAt(releasedChild.width,0)
                        }else if(offset<=0.5){//左边滑动
                            //设置捕获的控件的位置
                            mViewDragHelper?.settleCapturedViewAt(0,0)
                        }
                    }
                    LayoutSidingOrientation.BOTTOM -> {
                        val offset = releasedChild.top / releasedChild.height.toFloat()
                        if(offset>0.5){//下滑动
                            //设置捕获的控件的位置
                            mViewDragHelper?.settleCapturedViewAt(0,releasedChild.height)
                        }else if(offset<=0.5){//上滑动
                            //设置捕获的控件的位置
                            mViewDragHelper?.settleCapturedViewAt(0,0)
                        }
                    }
                    LayoutSidingOrientation.LEFT -> {
                        val offset = releasedChild.right / releasedChild.width.toFloat()
                        if(offset>0.5){//右边滑动
                            //设置捕获的控件的位置
                            mViewDragHelper?.settleCapturedViewAt(0,0)
                        }else if(offset<=0.5){//左边滑动
                            //设置捕获的控件的位置
                            mViewDragHelper?.settleCapturedViewAt(-releasedChild.width,0)
                        }
                    }
                }
                invalidate()
            }
        }

        override fun onViewDragStateChanged(state: Int) {
            super.onViewDragStateChanged(state)
            mContentViewState = state
        }

        override fun getViewHorizontalDragRange(child: View): Int {
            return child.width
        }

        override fun onEdgeDragStarted(edgeFlags: Int, pointerId: Int) {
            super.onEdgeDragStarted(edgeFlags, pointerId)
            if(mContentViewState == ViewDragHelper.STATE_IDLE){//停止状态
                //捕获指定的控件
                mContentView?.let { mViewDragHelper?.captureChildView(it,pointerId) }
            }
        }



    }

    enum class LayoutSidingOrientation{
        TOP,//上划出
        BOTTOM,//下划出
        LEFT,//左划出
        RIGHT//右划出
    }
}